import { getArticleList, getNewList } from "@/store/actions/home";
import { RootState } from "@/types/store";
// import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import ArticleItem from "../ArticleItem";
import { InfiniteScroll, PullToRefresh } from "antd-mobile";
import styles from "./index.module.scss";
import { useHistory } from "react-router-dom";
type Props = {
  channelId: number;
};
const ArticleList = ({ channelId }: Props) => {
  const history = useHistory();
  const dispatch = useDispatch();
  const { channelArticles } = useSelector((state: RootState) => state.home);
  console.log(channelArticles);
  const { articles = [], timestamp } = channelArticles[channelId] || {};
  //! 获取文章列表数据,下面使用了无限滚动，所以初次刷新去除
  // useEffect(() => {
  //   dispatch(getArticleList(channelId, Date.now() + ""));
  // }, [dispatch, channelId]);
  // 触底之后继续获取数据
  const hasMore = timestamp === null ? false : true;
  // const hasMore = true;
  // 必须返回一个Promise对象
  const loadMore = async () => {
    await console.log("加载更多数据", hasMore);
    await dispatch(getArticleList(channelId, timestamp || Date.now() + ""));
  };
  const onRefresh = async () => {
    // 重置当前频道的数据，重新加载第一页的数据
    await dispatch(getNewList(channelId, Date.now() + ""));
  };
  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <PullToRefresh onRefresh={onRefresh}>
        {articles.map((item) => (
          <div onClick={() => history.push(`/article/${item.art_id}`)} key={item.art_id} className="article-item">
            <ArticleItem article={item} />
          </div>
        ))}
        {/* 无限加载组件 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  );
};

export default ArticleList;
